<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

/**
 * @method static canUse(\Illuminate\Contracts\Auth\Authenticatable|null $user) Builder
 */
class CustomerCoupon extends Model
{
    protected $with = ['coupons'];

    protected $fillable = ['customer_id', 'coupon_id', 'expired_at'];

    protected $casts = [
        'expired_at' => 'datetime'
    ];

    public function scopeCanUse(Builder $builder, Customer $customer, $coupon_ids = [])
    {
        $query = $builder->whereDate('expired_at', '>', now())
            ->whereCustomerId($customer->id)
            ->whereIsUsed(false);

        if ($coupon_ids) {
            $query->whereIn('coupon_id', $coupon_ids);
        }

        return $query;
    }

    public function scopeHasReceiveCoupon(Builder $builder, Customer $customer, Coupon $coupon)
    {
        return $builder->create([
            'customer_id' => $customer->id,
            'coupon_id' => $coupon->id,
            'expired_at' => now()->addDays(3),
        ]);
    }

    public function scopeCanUseOnProduct(Builder $builder, Product $product, $price = 0.00)
    {
        $coupons = $product->coupons->map(function ($coupon) use ($price) {
            return $price ?
                $coupon->min_amount < $price ? $coupon->id : null
                : $coupon->id;
        });
        return in_array($this->id, $coupons->toArray());
    }

    public function coupons()
    {
        return $this->belongsTo(Coupon::class, 'coupon_id');
    }
}
